package Linux五种IO模型.reactor2;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

/**
 * @author coderFu
 * @create 2022/3/8
 *
 * 在里这里面的读写操作利用多线程来完成
 */
public class HandlerDemo2 implements Runnable {

    private final SocketChannel socketChannel;

    private HandlerState state;

    private final SelectionKey key;



    public HandlerDemo2(SocketChannel socketChannel, SelectionKey key){
        this.socketChannel = socketChannel;
        this.key = key;
        // 标识是读取状态还是 写入状态。
        state = new ReadState();
    }


    @Override
    public void run() {

        try {
            // 调用state 中的 Handle 方法
            state.handle(this,key,socketChannel,ReactorThreadPool.getThreadPoolExecutor());

        } catch (IOException e) {
            System.out.println("出现了异常，关闭");
            closeChannel();
            e.printStackTrace();
        }


    }

    public void closeChannel(){
        try {
            socketChannel.close();
            key.cancel();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void setState(HandlerState state){
        this.state = state;
    }
}
